/*
   Copyright (C) 2011 Roman Belov <romblv@gmail.com>

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdint.h>
#include <stdlib.h>
#include <limits.h>

#include "util/rand.h"

#ifdef CHAR_BIT
# define RAND_UINT_BIT	(sizeof(unsigned int) * CHAR_BIT)
#else
# define RAND_UINT_BIT	(sizeof(unsigned int) * 8)
#endif

int rand_seed;

static void
rand_just_gen()
{
	rand_seed = rand_seed * 17317 + 1;
}

int rand_gen_from_to(int from, int to)
{
	int	len = to - from + 1;
	int	val;

	rand_just_gen();
	val = (((unsigned int) rand_seed) / USHRT_MAX) % len;

	return from + val;
}

int rand_gen_binary()
{
	unsigned int	val;
	int		bit = 0;
	int		i;

	rand_just_gen();

	val = (unsigned int) rand_seed;

	for (i = 0; i < RAND_UINT_BIT; ++i, val >>= 1) {
		bit ^= val & 1;
	}

	return bit;
}

